using System;
using System.Collections.Generic;
using System.Text;

namespace NBusiness.Query.SqlServer
{
    public class SqlTable : ITable
    {
        #region Member fields and properties
        private string _name;
        private string _alias; 
        #endregion

        #region Constructors
        public SqlTable() { }
        public SqlTable(string name)
            : this(name, null)
        { }
        public SqlTable(string name, string alias)
        {
            _name = name;
            _alias = alias;
        }
        #endregion

        #region ITable Members

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Alias
        {
            get { return _alias; }
            set { _alias = value; }
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext());
        }
        public string ToSql(IQueryContext context)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("[" + _name + "]");
            (context as SqlQueryContext).EnsureAlias(this);
            builder.Append(" AS [" + _alias + "]");

            return builder.ToString();
        }

        #endregion

        #region Operator overloads
        public static SqlSelect operator &(SqlTable table, SqlBoolean e)
        {
            return new SqlSelect().From(table).Where(e) as SqlSelect;
        } 
        #endregion

        #region ISource Members
        public IQuery Where(IExpression expression)
        {
            return new SqlSelect().From(this).Where(expression);
        }

        public IQuery OrderBy(IOrder orderBy)
        {
            return new SqlSelect().From(this).OrderBy(orderBy);
        }
        public IQuery OrderBy(SortOrder order, params IColumn[] columns)
        {
            return new SqlSelect().From(this).OrderBy(order, columns);
        }

        public IQuery GroupBy(params IColumn[] groupBy)
        {
            return new SqlSelect().From(this).GroupBy(groupBy);
        }

        public IQuery Join(IJoin join)
        {
            return new SqlSelect().From(this).Join(join);
        }

        public IQuery Select(params ISelectable[] selectable)
        {
            return new SqlSelect().From(this).Select(selectable);
        }

        #endregion

        #region ITable Members

        public ITable As(string alias)
        {
            _alias = alias;
            return this;
        }
        #endregion

        #region Object overrides
        public override string ToString()
        {
            return ToSql();
        }
        #endregion
    }
}
